package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.Album;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.service.TimeLineService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi{
    //评论数据存储在Redis中key的前缀
    private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";

    //用户是否点赞的前缀
    private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";

    //用户是否喜欢的前缀
    private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdService idService;
    @Autowired
    private TimeLineService timeLineService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public PageInfo<Publish> queryPublishList(Long userId, Integer page, Integer pageSize) {
        // 在时间线表查询好友动态
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        // 条件查询
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("date")));
        Query query = new Query().with(pageable);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        if (CollUtil.isEmpty(timeLineList)) {
            // 没有查到好友动态的
            return pageInfo;
        }

        // 获取时间线表中的发布id的列表
        List<Object> ids = CollUtil.getFieldValues(timeLineList, "publishId");
        // 根据动态id查询好友动态
        Query queryPublish = Query.query(Criteria.where("id").in(ids)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = mongoTemplate.find(queryPublish, Publish.class);

        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    // 发布动态，返回成功的动态id
    @Override
    public String savePublish(Publish publish) {
        // 对publish进行校验
        if (!ObjectUtil.isAllNotEmpty(publish.getText(), publish.getUserId())) {
            // 有一个为空，发布失败
            return null;
        }

        // 设置主键Id
        publish.setId(ObjectId.get());

        try {
            // 设置自增长的pid
            publish.setPid(this.idService.createId(IdType.PUBLISH));
            publish.setCreated(System.currentTimeMillis());

            // 写入到publish表中
            this.mongoTemplate.save(publish);

            // 写入到相册表
            Album album = new Album();
            album.setId(ObjectId.get());
            album.setCreated(System.currentTimeMillis());
            album.setPublishId(publish.getId());

            this.mongoTemplate.save(album, "quanzi_album_" + publish.getUserId());

            // 异步写入到好友的时间线表
            this.timeLineService.saveTimeLine(publish.getUserId(), publish.getId());
        } catch (Exception e) {
            //TODO 需要做事务的回滚，Mongodb的单节点服务，不支持事务，对于回滚我们暂时不实现了
            log.error("发布动态失败 " + publish, e);
        }
        return publish.getId().toHexString();
    }

    // 查询推荐动态
    @Override
    public PageInfo<Publish> queryRecommendPublishList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Publish> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        // 从Redis中查询推荐的结果数据
        String key = "QUANZI_PUBLISH_RECOMMEND_" + userId;
        String data = redisTemplate.opsForValue().get(key);
        if (StrUtil.isEmpty(data)) {
            // 为空
            return pageInfo;
        }

        // 查询Pid后进行分页
        List<String> pids = StrUtil.split(data, ',');
        // 计算分页
        int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
        // 开始
        int startIndex = startEnd[0];
        // 结束
        int endIndex = Math.min(startEnd[1], pids.size());


        ArrayList<Long> pidLongList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            pidLongList.add(Long.valueOf(pids.get(i)));
        }
        if (CollUtil.isEmpty(pidLongList)) {
            // 没有查询到数据
            return pageInfo;
        }

        // 根据pid查询publish
        Query query = Query.query(Criteria.where("pid").in(pidLongList)).with(Sort.by(Sort.Order.desc("created")));
        List<Publish> publishList = this.mongoTemplate.find(query, Publish.class);
        if (CollUtil.isEmpty(publishList)) {
            // 没有查询到数据
            return pageInfo;
        }

        pageInfo.setRecords(publishList);
        return pageInfo;
    }

    // 根据id查询动态
    @Override
    public Publish queryPublishById(String id) {
        return mongoTemplate.findById(new ObjectId(id), Publish.class);
    }


    private String getCommentRedisKeyPrefix(String publishId) {
        return COMMENT_REDIS_KEY_PREFIX + publishId;
    }

    private String getCommentUserLikeRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LIEK_REDIS_KEY_PREFIX + userId;
    }

    private String getCommentUserLoveRedisKeyPrefix(Long userId) {
        return COMMENT_USER_LOVE_REDIS_KEY_PREFIX + userId;
    }

    // 点赞
    @Override
    public Boolean likeComment(Long userId, String publishId) {
        // 判断该用户是否已经点赞，如果已经点赞就直接返回
        if (queryUserIsLike(userId, publishId)) {
            return false;
        }

        // 保存Comment
        Boolean result = saveComment(userId, publishId, CommentType.LIKE, null);
        if (!result) {
            return false;
        }
        // 修改redis中的点赞数以及是否点赞
        // 修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
        // 用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }

    // 取消点赞
    @Override
    public Boolean disLikeComment(Long userId, String publishId) {
        // 判断该用户是否已经点赞，如果没有点赞就直接返回
        if (!queryUserIsLike(userId, publishId)) {
            return false;
        }

        // 删除Comment
        Boolean result = removeComment(userId, publishId, CommentType.LIKE);
        if (!result) {
            return false;
        }
        // 修改Redis中的数据
        // 修改点赞数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        redisTemplate.opsForHash().increment(redisKey, hashKey, -1);

        // 用户是否点赞
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey, userHashKey);

        return true;
    }

    // 查询点赞数
    @Override
    public Long queryLikeCount(String publishId) {
        // 查询redis，如果命中直接返回
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LIKE.toString();
        Object data = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return Convert.toLong(data);
        }

        // 从Mongodb中查询
        Long count = queryCommentCount(publishId, CommentType.LIKE);
        // 写入redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));

        return count;
    }

    // 查询用户是否点赞该动态
    @Override
    public Boolean queryUserIsLike(Long userId, String publishId) {
        // 查询redis，如果命中直接返回
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String userHashKey = getCommentUserLikeRedisKeyPrefix(userId);
        Object data = redisTemplate.opsForHash().get(redisKey, userHashKey);
        if (ObjectUtil.isNotEmpty(data)){
            return StrUtil.equals(Convert.toStr(data),"1");
        }

        // 查询Mongodb，确定是否已经点赞
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("userId").is(userId)
                .and("commentType").is(CommentType.LIKE)
        );
        long count = this.mongoTemplate.count(query, Comment.class);
        if(count == 0){
            return false;
        }

        // 写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");

        return true;
    }


    // 保存Comment
    private Boolean saveComment(Long userId,String publishId, CommentType commentType, String content) {
        try {
            Comment comment = new Comment();
            comment.setId(ObjectId.get());
            comment.setPublishId(new ObjectId(publishId));
            // 评论人的id
            comment.setUserId(userId);
            // 评论的类型
            comment.setCommentType(commentType.getType());
            // 评论的内容
            comment.setContent(content);
            comment.setCreated(System.currentTimeMillis());

            Publish publish = queryPublishById(publishId);
            //TODO 其他评论对象，暂不处理
            comment.setPublishUserId(publish.getUserId());

            mongoTemplate.save(comment);
            return true;
        } catch (Exception e) {
            log.error("保存Comment时出现错误 userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
        }
        return false;
    }

    // 删除Comment
    private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(publishId))
                .and("commentType").is(commentType.getType())
        );
        return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
    }

    // 通过Mongodb查询点赞数
    private Long queryCommentCount(String publishId, CommentType commentType) {
        Query query = Query.query(Criteria.where("publishId").is(publishId)
        .and("commentType").is(commentType.getType()));
        return mongoTemplate.count(query,Comment.class);
    }


    // 喜欢
    @Override
    public Boolean loveComment(Long userId, String publishId) {
        // 判断该用户是否已经喜欢，如果已经喜欢就直接返回
        if (queryUserIsLove(userId, publishId)){
            return false;
        }

        // 保存喜欢
        Boolean result = saveComment(userId, publishId, CommentType.LOVE, null);
        if (!result){
            // 保存没有成功
            return false;
        }

        // 修改redis中的喜欢数和用户是否喜欢
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,1);
        // 用户是否喜欢
        String userHashKey = getCommentUserLoveRedisKeyPrefix(userId);
        redisTemplate.opsForHash().put(redisKey,userHashKey,"1");

        return true;
    }

    // 取消喜欢
    @Override
    public Boolean disLoveComment(Long userId, String publishId) {
        // 判断用户是否已经喜欢
        if (!queryUserIsLove(userId, publishId)){
            return false;
        }

        // 删除喜欢
        Boolean result = removeComment(userId, publishId, CommentType.LOVE);
        if (!result){
            // 删除失败
            return false;
        }

        // 修改redis中数据
        // 修改喜欢数
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        redisTemplate.opsForHash().increment(redisKey,hashKey,-1);
        //  修改用户是否喜欢
        String userHashKey = getCommentUserLoveRedisKeyPrefix(userId);
        redisTemplate.opsForHash().delete(redisKey,userHashKey);

        return true;
    }

    // 查询喜欢数
    @Override
    public Long queryLoveCount(String publishId) {
        // 查询redis，如果有，直接返回，没有就查询mongdb
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)){
            return Convert.toLong(value);
        }

        // 从Mongodb中查询
        Long count = queryCommentCount(publishId, CommentType.LOVE);
        // 储存到redis中
        redisTemplate.opsForHash().put(redisKey,hashKey,String.valueOf(count));

        return count;
    }

    // 查询用户是否喜欢该动态
    @Override
    public Boolean queryUserIsLove(Long userId, String publishId) {
        // 查询redis，如果有，直接返回，没有就查询mongdb
        String redisKey = getCommentRedisKeyPrefix(publishId);
        String hashKey = CommentType.LOVE.toString();
        Object value = redisTemplate.opsForHash().get(redisKey, hashKey);
        if (ObjectUtil.isNotEmpty(value)){
            return StrUtil.equals(Convert.toStr(value),"1");
        }

        // 从mongodb中查询,
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                                    .and("userId").is(userId)
                                    .and("commentType").is(CommentType.LOVE.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        if (count == 0){
            return false;
        }

        // 写入到redis中
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");
        return true;
    }

    // 查询评论列表
    @Override
    public PageInfo<Comment> queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));

        // 查询评论列表
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                                    .and("commentType").is(CommentType.COMMENT.getType())).with(pageRequest);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(commentList);

        return pageInfo;
    }

    // 发表评论
    @Override
    public Boolean saveComment(Long userId, String publishId, String content) {
        return saveComment(userId,publishId,CommentType.COMMENT,content);
    }
}
